package com.catering.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.catering.dao.*;
import com.catering.entity.*;
import com.catering.entity.vo.CateringOrderVo;
import com.catering.service.CateringOrderService;
import com.catering.until.CommonUtils;
import com.catering.until.ResultData;
import com.catering.until.ResultEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class CateringOrderServiceImpl extends ServiceImpl<CateringOrderDao, CateringOrder> implements CateringOrderService {
	
	@Autowired
	private CateringOrderDao cateringOrderDao;
	@Autowired
	private CateringOrderCartDao cateringOrderCartDao;
	@Autowired
	private CateringCartDao cateringCartDao;
	@Autowired
	private CateringOrderLogDao cateringOrderLogDao;
	@Autowired
	private CateringSpacesChildDao cateringSpacesChildDao;
	@Autowired
	private CateringGoodsDao cateringGoodsDao;

	@Override
	public ResultData select(Map<String,String> map) {
		try {
			QueryWrapper wrapper = CommonUtils.getKeySet(map,"t1");
			List<CateringOrderVo> list = new ArrayList<CateringOrderVo>();
			Integer count =0;
			if(CommonUtils.checkNoNull(map.get("page"))) {
				IPage<CateringOrder> page = new Page<>(Integer.valueOf(map.get("page")),Integer.valueOf(map.get("limit")));
				IPage<CateringOrderVo> pageList = cateringOrderDao.selectPageList(page, wrapper);
				count = cateringOrderDao.selectPageCount(wrapper);
				list = pageList.getRecords();
			}else {
				list = cateringOrderDao.selectNoPageList(wrapper);
			}
			list = cancelOrder(list);
			for(CateringOrderVo vo : list){
				Map map1 = new HashMap();
				QueryWrapper queryWrapper = new QueryWrapper();
				queryWrapper.eq("t1.order_id",vo.getSysId());
				List<CateringOrderCart> cartList = cateringOrderCartDao.selectNoPageList(queryWrapper);
				for(CateringOrderCart cart : cartList){
					if(CommonUtils.checkNoNull(cart.getSpacesId())){
						CateringSpacesChild cw = new CateringSpacesChild();
						cw.setSysIds(Arrays.stream(cart.getSpacesId().split(",")).collect(Collectors.toList()));
						List<CateringSpacesChild> childList = cateringSpacesChildDao.selectNameList(cw);
						cart.setSpacesName(childList.stream().map(CateringSpacesChild::getSpacesName).collect(Collectors.joining(",")));
					}
				}
				vo.setCartList(cartList);
				List<CateringOrderLog> logList = cateringOrderLogDao.selectList(new LambdaQueryWrapper<CateringOrderLog>().eq(CateringOrderLog::getOrderId,vo.getSysId()).orderByAsc(CateringOrderLog::getOrderStatus));
				vo.setLogList(logList);
			}
			return ResultData.success(list,count);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ResultData.error(ResultEnum.SERVER_ERROR.getCode(),ResultEnum.SERVER_ERROR.getMsg());
	}

	//检查未支付的订单是否超时，否则取消
	public List<CateringOrderVo> cancelOrder(List<CateringOrderVo> list){
		for(CateringOrderVo vo : list){
			Long diff = CommonUtils.dateDiff(vo.getCreateTime(),CommonUtils.getTime(19),"");
			CateringOrder order = JSON.parseObject(JSON.toJSONString(vo),CateringOrder.class);
			if(diff >= 900 && order.getStatus() == 0 ){
				order.setStatus(2);
				order.setOrderStatus("ORDER_STATUS_00");
				vo.setStatus(2);
				cateringOrderDao.updateById(order);
				//增加对应的订单取消 物流信息
				CateringOrderLog log = new CateringOrderLog();
				log.setOrderId(vo.getSysId());
				log.setSysId(CommonUtils.getUuid());
				log.setOrderStatus("ORDER_STATUS_00");
				log.setCreateTime(CommonUtils.addDateTimeToStr(CommonUtils.stringToDate(vo.getCreateTime(),"yyyy-MM-dd HH:mm:ss:SSS"),0,0,15,0,"yyyy-MM-dd HH:mm:ss:SSS"));
				cateringOrderLogDao.insert(log);
			}
		}
		return list;
	}

	@Override
	public ResultData selectOrder(Map<String,String> map) {
		try {
			QueryWrapper wrapper = CommonUtils.getKeySet(map,"t1");
			List<CateringOrderVo> list = cateringOrderDao.selectNoPageList(wrapper);
			for(CateringOrderVo vo : list){
				Map map1 = new HashMap();
				QueryWrapper queryWrapper = new QueryWrapper();
				queryWrapper.eq("t1.order_id",vo.getSysId());
				List<CateringOrderCart> cartList = cateringOrderCartDao.selectNoPageList(queryWrapper);
				for(CateringOrderCart cart : cartList){
					if(CommonUtils.checkNoNull(cart.getSpacesId())){
						CateringSpacesChild cw = new CateringSpacesChild();
						cw.setSysIds(Arrays.stream(cart.getSpacesId().split(",")).collect(Collectors.toList()));
						List<CateringSpacesChild> childList = cateringSpacesChildDao.selectNameList(cw);
						cart.setSpacesName(childList.stream().map(CateringSpacesChild::getSpacesName).collect(Collectors.joining(",")));
					}
				}
				vo.setCartList(cartList);
				List<CateringOrderLog> logList = cateringOrderLogDao.selectList(new LambdaQueryWrapper<CateringOrderLog>().eq(CateringOrderLog::getOrderId,vo.getSysId()).orderByAsc(CateringOrderLog::getCreateTime));
				vo.setLogList(logList);
			}
			return ResultData.success(list);
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ResultData.error(ResultEnum.SERVER_ERROR.getCode(),ResultEnum.SERVER_ERROR.getMsg());
	}

	@Override
	public ResultData insert(Map<String,Object> map) {
		try {
			CateringOrder vo = JSON.parseObject(JSON.toJSONString(map), CateringOrder.class);
			vo.setSysId(CommonUtils.getUuid());
			vo.setOrderNo(getCardNo());
			vo.setCreateTime(CommonUtils.getTime(19));
			cateringOrderDao.insert(vo);
			for(CateringOrderCart cart : vo.getOrderCartList()){
				cart.setOrderId(vo.getSysId());
				if(CommonUtils.checkNoNull(cart.getSpacesId())){
					List<CateringSpacesChild> spacesChildList = cateringSpacesChildDao.selectList(new LambdaQueryWrapper<CateringSpacesChild>().eq(CateringSpacesChild::getSysId, Arrays.stream(cart.getSpacesId().split(","))
							.collect(Collectors.toList())));
					cart.setSpacesName(spacesChildList.stream().map(CateringSpacesChild::getSpacesName).collect(Collectors.joining(",")));
				}
				cart.setCreateTime(CommonUtils.getTime(19));
				cateringOrderCartDao.insert(cart);
				//新增订单成功之后减少商品对应的库存,增加对应的商品销量
				CateringGoods goods = cateringGoodsDao.selectById(cart.getGoodsId());
				goods.setGoodsStock(goods.getGoodsStock()-cart.getGoodsNum());
				goods.setSaleNum(goods.getSaleNum() + cart.getGoodsNum());
				cateringGoodsDao.updateById(goods);
			}
			//删除购物车的商品
			cateringCartDao.delete(new LambdaQueryWrapper<CateringCart>().eq(CateringCart::getUserId,vo.getUserId()));
			//新增订单物流信息
			CateringOrderLog log = new CateringOrderLog();
			log.setOrderId(vo.getSysId());
			log.setSysId(CommonUtils.getUuid());
			log.setOrderStatus("ORDER_STATUS_01");
			log.setCreateTime(CommonUtils.getTime(23));
			cateringOrderLogDao.insert(log);
			return ResultData.success(vo.getSysId());
		}catch (Exception e) {
			e.printStackTrace();
			return ResultData.error(ResultEnum.INSERT_ERROR.getCode(),ResultEnum.INSERT_ERROR.getMsg());
		}
	}

	private String getCardNo() {
		return CommonUtils.getRandomByTime("DD");
	}

	@Override
	public ResultData update(Map<String,String> map) {
		try {
			CateringOrder vo = JSON.parseObject(JSON.toJSONString(map), CateringOrder.class);
			CateringOrder order = cateringOrderDao.selectById(vo.getSysId());
			cateringOrderDao.updateById(vo);
			//当原本订单状态为0（待支付）和传入参数为2（取消）
			if(order.getStatus() == 0 && vo.getStatus() == 2){
				List<CateringOrderCart> cartList = cateringOrderCartDao.selectList(new LambdaQueryWrapper<CateringOrderCart>().eq(CateringOrderCart::getOrderId,vo.getSysId()));
				for(CateringOrderCart cart : cartList){
					//超时或者取消订单成功之后增加商品对应的库存
					CateringGoods goods = cateringGoodsDao.selectById(cart.getGoodsId());
					goods.setGoodsStock(goods.getGoodsStock()+cart.getGoodsNum());
					goods.setSaleNum(goods.getSaleNum() - cart.getGoodsNum());
					cateringGoodsDao.updateById(goods);
				}
			}
			return ResultData.success();
		}catch (Exception e) {
			e.printStackTrace();
			return ResultData.error(ResultEnum.UPDATE_ERROR.getCode(),ResultEnum.UPDATE_ERROR.getMsg());
		}
	}

	@Override
	public ResultData updateStatus(Map<String,String> map) {
		try {
			CateringOrder vo = JSON.parseObject(JSON.toJSONString(map), CateringOrder.class);
			List<String> oders = Arrays.asList(vo.getOrderStatus().split(","));
			if(oders.size() > 1){
				for(String o : oders){
					vo.setOrderStatus(o);
					insertLog(vo);
				}
				cateringOrderDao.updateById(vo);
			}else{
				cateringOrderDao.updateById(vo);
				insertLog(vo);
			}
			return ResultData.success(vo.getSysId());
		}catch (Exception e) {
			e.printStackTrace();
			return ResultData.error(ResultEnum.INSERT_ERROR.getCode(),ResultEnum.INSERT_ERROR.getMsg());
		}
	}

	/**
	 * 新增订单物流信息
	 * @param vo
	 */
	private void insertLog(CateringOrder vo){
		CateringOrderLog log = new CateringOrderLog();
		log.setOrderId(vo.getSysId());
		log.setSysId(CommonUtils.getUuid());
		log.setOrderStatus(vo.getOrderStatus());
		log.setCreateTime(CommonUtils.getTime(23));
		cateringOrderLogDao.insert(log);
	}

	@Override
	public ResultData delete(Map<String,String> map) {
		try {
			CateringOrder vo = JSON.parseObject(JSON.toJSONString(map), CateringOrder.class);
			List<String> list = Stream.of(vo.getSysId().split(",")).collect(Collectors.toList());
			cateringOrderDao.deleteBatchIds(list);
			return ResultData.success();
		}catch (Exception e) {
			e.printStackTrace();
		}
		return ResultData.error(ResultEnum.DELETE_ERROR.getCode(),ResultEnum.DELETE_ERROR.getMsg());
	}
}
